package com.jackstraw.jack_base.rules.threadpool;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author : zzhao
 * @date :Create in 2022/12/04 23:00
 * @description: 线程池拒绝策略，当线程池满了，且队列也满了，此处自定义是不抛弃任务，让当前线程执行，并且记录日志
 * @package com.jackstraw.jack_base.rules.threadpool
 * @className MasterExecutionHandler
 */
@Slf4j
public class ExecutionHandler implements RejectedExecutionHandler {
    /**
     * 重写拒绝策略
     *
     * @param r 当前提交任务的线程
     * @param e 线程池对象
     */
    @Override
    public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
        if (!e.isShutdown()) {
            String content = String.format("Thread Pool is EXHAUSTED!" +
                            "Pool Size: %d,(active: %d,core :%d,max :%d,largest :%d),Task:%d(completed :$d)," +
                            "Executor status:(isShutdown: %s, isTerminated: %s, isTerminating: %s)"
                    , e.getPoolSize(), e.getActiveCount(), e.getCorePoolSize(), e.getMaximumPoolSize(), e.getLargestPoolSize()
                    , e.getTaskCount(), e.getCompletedTaskCount(), e.isShutdown(), e.isTerminated(), e.isTerminating());
            log.warn(content);
            r.run();
        }
    }
}
